<template>
  <div class="main">
    <div v-if="!isloaded">Loading...</div>
    <Picture v-for="item in imgData" :item="item" v-if="isSearchTab" class="animate__animated animate__fadeIn">
    </Picture>

    <Picture v-for="item in myImg" :item="item" v-if="!isSearchTab && !isNoImg"
      class="animate__animated animate__fadeIn">
    </Picture>
    <div v-if="!isSearchTab && isNoImg" class="no-img">
      <span>该路径下暂时没有图片</span>
    </div>

  </div>
</template>

<script setup lang="ts">
import Picture from "@/components/Home/Picture.vue";
import { get } from "@/tools/api/api";
import { ref, reactive, getCurrentInstance, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { usePhotoStore } from "@/store/photo";
import throttle from "lodash/throttle";
import debounce from "lodash/debounce";
import { myImgType, imgTypeType, imgDataType, getImgByFolderParamsType } from "@/components/Home/type";
/**
 * 初始化组件
 */
// 创建实例
const instance = getCurrentInstance();
//引入仓库
const photoStore = usePhotoStore()
onMounted(() => {
  if (photoStore.searchKeyWords) {
    getImgParams.kw = photoStore.searchKeyWords
    searchImg();
  }
  // 收藏夹选择组件配置
  photoStore.$patch((state) => {
    state.showAllLevel = true
    state.searchPage = 1;
  })
  if (!photoStore.isSearchTab) {
    // 我的
    getMyImg();
  }
  // 添加滚动监听
  photoStore.page = 1
  window.addEventListener("scroll", scrollLoad)
})
// 页面销毁，取消滚动监听
onUnmounted(() => {
  window.removeEventListener("scroll", scrollLoad)
})

// 加载中
const isloaded = ref<boolean>(false);

// 判断路径下是否有图片
const isNoImg = ref<boolean>(false)

/**
 * tab信息
 */
const isSearchTab = ref<boolean>(true)
instance?.proxy?.$Bus.on("onClickTab", (value: any) => {
  isSearchTab.value = value;
  window.removeEventListener("scroll", scrollLoad)
  window.addEventListener("scroll", scrollLoad)
  upToDate();
  if (isSearchTab.value) {
    // 发现
    photoStore.searchPage = 1;
  } else if (!isSearchTab.value) {
    // 我的
    isNoImg.value = false;
    getMyImg();
  }

})
// 更新数据
instance?.proxy?.$Bus.on("reload", () => {
  upToDate();
})

// 更新
const upToDate = () => {
  if (!isSearchTab.value) {
    // 我的
    getMyImg();
  } else if (isSearchTab.value) {
    // 发现
    searchImg()
  }
}

/**
 * 无限滚动加载
 */
const scrollLoad = () => {
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  let clientHeight = document.documentElement.clientHeight;
  let scrollHeight = document.documentElement.scrollHeight;
  if (scrollTop + clientHeight >= scrollHeight - 10) {
    //滚动到底部
    if (photoStore.isSearchTab) {
      // 发现
      searchImg();
    } else if (!photoStore.isSearchTab) {
      // 我的
      upToDate()
    }
  }
}



/**
 * my相关
 */
// 图片数据
const myImg = ref<myImgType[]>([])
//获取选中的收藏夹
const selectedFolder = ref<string[]>([])
instance?.proxy?.$Bus.on("selectedFolderData", (value: any) => {
  photoStore.page = 1;
  myImg.value = [];
  selectedFolder.value = value;
  getMyImg()
  window.removeEventListener("scroll", scrollLoad)
  window.addEventListener("scroll", scrollLoad)
})
// 发送网络请求，获取选中收藏夹内所有图片
const getMyImgParams = reactive<getImgByFolderParamsType>({
  favorite: '',
  page: 1,
  limit: 20
})
const getMyImg = throttle(() => {
  if (photoStore.currentFolder?.length === 3) {
    // 选择最小收藏夹
    getMyImgParams.favorite = photoStore.currentFolder[photoStore.currentFolder.length - 1]
  } else if (photoStore.currentFolder?.length === 1 || photoStore.currentFolder?.length === 2) {
    isNoImg.value = true
    myImg.value = []
    return
  } else if (!photoStore.currentFolder?.length) {
    // 没有选择目录  根目录
    getMyImgParams.favorite = '-1';
  }
  getMyImgParams.limit = photoStore.limit;
  getMyImgParams.page = photoStore.page;
  get("getImg", getMyImgParams).then((res: any) => {
    if (res.code === 100) {
      // 接口请求成功
      isloaded.value = true;
      if (!res.data?.length && res.page == 1) {
        ElMessage.warning("暂时还没有收藏的图片！")
        isNoImg.value = true
        return
      }
      isNoImg.value = false;
      // 没有更多图片
      if (res.data?.length < photoStore.limit) {
        window.removeEventListener("scroll", scrollLoad);
      }
      if (res.data && res.page == 1) {
        myImg.value = res.data.reverse()
        photoStore.$patch((state) => {
          state.page++;
          state.myImgData = res.data.reverse();
        })
      } else {
        if (res.page == photoStore.page) {
          myImg.value.push.apply(myImg.value, res.data)
          photoStore.$patch((state) => {
            state.page++;
            state.myImgData = res.data.reverse();
          })
        }
      }
    } else ElMessage.error(res.msg)
  })
}, 1000)

/**
 * search相关
 */

// 拿到搜索框的内容
instance?.proxy?.$Bus.on("searchContent", (value: any) => {
  getImgParams.kw = value
  isSearchTab.value = photoStore.isSearchTab
  searchImg();
})

/**
 * 根据关键字搜索图片
 */

//图片类别
const imgType = ref<imgTypeType[]>([])
// 图片url
const imgData = ref<imgDataType[]>([])
// 参数类型
type getImgParamsType = {
  kw: string,    //搜索关键字
  page: number,  //当前页数
  per_page?: number,//每页图片数量，可不填默认为24
  sort?: string//图片分类，可不填
}
// 请求参数
const getImgParams = reactive<getImgParamsType>({
  kw: '金毛',
  page: 1,
  per_page: 11,
  sort: ''
})
// 发送网络请求
const searchImg = throttle(() => {
  getImgParams.page = photoStore.searchPage
  get("newImg", getImgParams).then((res: any) => {
    if (res.code === 100) {
      isloaded.value = true;
      if (res.data.page == 1) {
        imgData.value = res.data.img;
        photoStore.$patch((state) => {
          state.searchPicture = res.data.img;
          state.searchPage++;
        })
      } else {
        if (res.data.page == photoStore.searchPage) {
          photoStore.$patch((state) => {
            imgData.value.push.apply(imgData.value, res.data.img);
            state.searchPicture.push.apply(state.searchPicture, res.data.img);
            state.searchPage++;
          })
        }
      }
    }
  })
}, 1000)



</script>

<style scoped lang="scss">
$header-height: 0.3rem;
$logo-width: 0.6rem;
$a-font-size: 0.08rem;

.main {
  height: auto;
  text-align: center;
  width: 100%;
  margin: $logo-width * 0.2 auto; // 剧中
  columns: 5; // 默认列数
  column-gap: $logo-width * 0.1; // 列间距
  overflow: auto;

  .no-img {
    margin-top: 0.2rem;
    font-size: 0.1rem;
  }
}

@media screen and (max-width:1024px) {
  .main {
    height: auto;
    text-align: center;
    width: 100%;
    margin: $logo-width * 0.2 auto; // 剧中
    columns: 3; // 默认列数
    column-gap: $logo-width * 0.1; // 列间距
  }
}

@media screen and (max-width:600px) {
  .main {
    height: auto;
    text-align: center;
    width: 100%;
    margin: $logo-width * 0.2 auto; // 剧中
    columns: 2; // 默认列数
    column-gap: $logo-width * 0.4; // 列间距
  }
}
</style>
